var createChatEle, createChatNotificationEle, getFriends, createChatUsersEle, addFriend, readChatMessage,
    findFriend, cleanContent, acceptFriendRequest, refuseToAccept, sendChatMessage, getDate, createEle,
    readAllChatMessage, createAddFriendEle, chatting, postStates, changeStatus, profileFriendChat, loadMoreArticle,
    readAllNotification, showMore;
$(document).ready(function () {
    $(function () {
        const followUserName = $("#loginedUserName").text();
    });
    /**
     * 显示更多评论
     */
    showMore = function(e){
        console.info($(e));
        $(e).parent().children("div").each(function () {
            if($(this).children("li").hasClass("d-none")){
                $(this).children("li").removeClass("d-none");
                $(e).addClass("d-none");
            }
        });
    };

    /**
     * 将所有通知设为已读
     */
    readAllNotification = function () {
        var userName = $("#loginedUserName").text();
        $.ajax({
            type: "POST",
            url: "request/message/readAll/notice/" + userName,
            success: function (result) {
                if (result === "OK") {
                    // 清空通知列表
                    $("#notification-list").empty();
                    $("#notification-number").text(0);
                }
            },
            error: function (e) {
                console.warn(e)
            }
        })
    };
    /**
     * 将聊天消息设为已读
     */
    readChatMessage = function (e) {
        // 将和这个用户的未读聊天消息设为已读
        let myName = $("#loginedUserName").text();
        let friendName = $(e).prev().children("a").text();
        // 找到和这个用户相关的聊天消息通知
        // 通知通知数量
        let count = 0;
        $("#chat-message").children("li").each(function () {
            let name = $(this).children(".notification-event").children("a").text();
            if (name === friendName) {
                count += 1;
                // 找到了同名的用户，移除
                $(this).empty();
                $("#chat-message").remove($(this));
            }
        });
        console.info("找到的同名用户聊天信息数量：" + count);
        // 减少通知数量
        number = $("#chat-number").text();
        $("#chat-number").text(parseInt(number) - count);
    };

    /**
     * 首页发表状态
     */
    postStates = function () {
        console.log("发表状态");
        let statesContent = $("#post-states").val().trim();
        // console.info("发布的内容：" + statesContent);
        if (statesContent !== null && statesContent !== "") {
            // 如果存在内容则发布,并且把图片也一并上传
            $("#states-form").submit();
            $("#states-form").ajaxForm(function (data) {
                console.info(data);
            });
        } else {
            xtip.msg("请填写需要发布的内容");
        }
    };
    /**
     * 首页加载更多文章
     */
    loadMoreArticle = function () {
        window.loadMoreArticles();
    };

    profileFriendChat = function (e) {
        // 获得好友名字
        let friendName = $(e).parent().parent().parent().parent().prev().children(".author-content").find(".author-name").text();
        // 根据名字触发右侧聊天栏的聊天事件
        $("#chat-users-small").children("li").each(function (index) {
            let who = $(this).children(".author-thumb").children("p").text();
            if (friendName === who) {
                console.log("下标为：" + index + " status:");
                // 触发点击事件
                $(this).get(0).click();
            }
        });
    };

    changeStatus = function (e) {
        let $children = $(e).children(".icon-status");
        console.log($children);
        let status;
        if ($children.hasClass("online")) {
            // 设置在线
            status = 1;
            $("#user-status").replaceWith(' <span class="icon-status online" id="user-status"></span>')
        } else if ($children.hasClass("away")) {
            // 设置离开
            status = 2;
            $("#user-status").replaceWith(' <span class="icon-status away" id="user-status"></span>')
        } else if ($children.hasClass("disconected")) {
            // 设置离线
            status = 0;
            $("#user-status").replaceWith(' <span class="icon-status disconected" id="user-status"></span>')
        } else if ($children.hasClass("status-invisible")) {
            // 设置隐身
            status = 3;
            $("#user-status").replaceWith(' <span class="icon-status status-invisible" id="user-status"></span>')
        }
        $.ajax({
            type: "POST",
            url: "update/status/" + status,
            success: function (result) {
                if (result === "OK") {
                    console.log("更改状态成功！");
                }
            },
            error: function (e) {
                console.log(e)
            }
        })
    };

    createChatEle = function (json, status, imgPath) {
        let $li;
        if (status === 1) {
            $li = $("<li class=\"my-message\"></li>");
        } else {
            $li = $("<li></li>");
        }

        let $div = $("<div class=\"author-thumb\"></div>");
        let $img = $("<img id='friend-img' style='width: 28px; height: 28px;' src=\"\" alt=\"author\" class=\"mCS_img_loaded\">");
        $img.attr("src", imgPath);

        $div.append($img);
        $li.append($div);

        $div = $("<div  class=\"notification-event\"></div>");
        let $span = $("<span class=\"chat-message-item\" style='font-size: 1.2em'></span>");
        $($.parseHTML(json.content, document, true)).appendTo($span);

        $div.append($span);
        $span = $("<span class=\"notification-date\"></span>");
        let $time = $("<time class=\"entry-date updated\"></time>");
        $time.text(json.time);
        $span.append($time);
        $div.append($span);
        $li.append($div);

        $("#chat-message-field").append($li);
        $("#show-content").scrollTop($("#show-content")[0].scrollHeight);
    };
    // 创建聊天通知的元素
    createChatNotificationEle = function (json, imgPath) {
        console.log("createChatNotificationEle...........")
        let $li = $("<li class=\"message-unread\"></li>");
        let $div = $("<div class=\"author-thumb\"></div>");
        let $img = $("<img src=\"\" width='34px' height='34px' alt=\"author\">");
        $img.attr("src", imgPath);
        $div.append($img);
        $li.append($div);
        $div = $("<div class=\"notification-event\"></div>");
        let $a = $("<a href=\"#\" class=\"h6 notification-friend\"> </a>");
        $a.text(json.A);
        let $span = $("<span class=\"chat-message-item\"></span>");
        $($.parseHTML(json.content, document, true)).appendTo($span);
        $div.append($a);
        $div.append($span);
        $span = $("<span class=\"notification-date\"></span>");
        let $time = $("<time class=\"entry-date updated\"></time>");
        $time.text(json.time);
        $span.append($time);
        $div.append($span);
        $li.append($div);

        $li.append('<span class="notification-icon">\n' +
            '                                        <svg class="olymp-chat---messages-icon">\n' +
            '                                            <use xlink:href="svg-icons/sprites/icons.svg#olymp-chat---messages-icon">\n' +
            '                                            </use>\n' +
            '                                        </svg>\n' +
            '                                </span>\n' +
            '                                <div class="more">\n' +
            '                                    <svg class="olymp-three-dots-icon">\n' +
            '                                        <use xlink:href="svg-icons/sprites/icons.svg#olymp-three-dots-icon">\n' +
            '                                        </use>\n' +
            '                                    </svg>\n' +
            '                                </div>');
        $("#chat-message").append($li);
    };
    getFriends = function (followUserName) {
        $.ajax({
            type: "GET",
            url: "friend/findAll/" + followUserName,
            success: function (result) {
                let $small = $("#chat-users-small");
                let $large = $("#chat-users-large");
                let friendNumber = $large.children("li").length;
                // 用于存放显示出来的好友名字
                let friendNameArray = [];
                console.log("查找的朋友的结果：" + result);
                // 转换为json数组
                let jsonResult = jQuery.parseJSON(result);
                // 如果两个长度相等，则表明没有新添加朋友，不需要操作
                if (jsonResult.length === friendNumber) {
                    return false;
                } else {
                    $large.children("li").each(function () {
                        let friendName = $(this).children(".author-status").children(".author-name").children().text();
                        friendNameArray.push(friendName);
                    });
                    // 如果不想等，表明删除或者新添了好友，则要进行操作
                    for (let i = 0; i < jsonResult.length; i++) {
                        if ($.inArray(jsonResult[i].userName, friendNameArray) === -1) {
                            // 如果等于-1，则表示不存在数组中，则进行更新显示操作

                        }
                    }
                }
            },
            error: function () {

            }
        })
    };
    // 创建右侧栏好友显示的标签
    createChatUsersEle = function () {

    };
    // 点击头像弹出聊天对话框
    chatting = function () {
        console.log("点击聊天。。。。。。。。。。")
        // 先清除<ul>标签中的内容，再获取用户与该好友的聊天记录
        $("#chat-message-field").empty();
        $("#message-content").val("");
        let friendName = $(this).children().find("p").text();
        let myName = $("#loginedUserName").text();
        var $now = $(this);
        $.ajax({
            type: "POST",
            url: "chat/get/" + myName + "/" + friendName,
            async: false,
            success: function (result) {
                let jsonResult = jQuery.parseJSON(result);
                console.log(jsonResult);
                for (let i = 0; i < jsonResult.length; i++) {
                    let json = jQuery.parseJSON(jsonResult[i].messageContent);
                    if (json.A === myName) {
                        let imgPath = $("#user-img").attr("src");
                        // 如果发送方是我
                        createChatEle(json, 1, imgPath)
                    } else {
                        let imgPath = $now.children(".author-thumb").find("img").attr("src");
                        console.log("好友图片地址：" + imgPath)
                        // 如果发送方不是我
                        createChatEle(json, 0, imgPath);
                    }
                }
            },
            error: function (e) {
            }
        });
        // 设置聊天的标题，显示与谁在聊天
        $("#chat-title").text(friendName);
        console.log(friendName);
        $('.popup-chat-responsive').toggleClass('open-chat');

        return false
    };
    addFriend = function () {
        // 首先判断是否已经是好友了，已经是好友的话，就不能重复添加，如果不是好友才能添加
        var name = document.getElementById("loginedUserName").innerText;
        var userName = $("#username").text();
        console.log(userName);
        if (name === userName) {
            alert("不能添加自己为好友！");
            return false;
        }
        $.ajax({
            type: "GET",
            url: "isFriend/" + name + "/" + userName,
            async: false,
            success: function (result) {
                console.log("result: " + result);
                if (result === "YES") {
                    // 表明有关系
                    alert("不能重复添加对方为好友");
                } else {
                    // 浏览器不支持WebSocket时
                    if (!window.WebSocket) {
                        return;
                    }
                    // 建立了连接
                    if (socket.readyState === WebSocket.OPEN) {
                        var message = {};
                        message.A = name;
                        message.B = userName;
                        message.flag = "1";
                        console.log(message);
                        socket.send(JSON.stringify(message));
                        alert("发送好友请求成功！等待对方通过中。。。");
                    } else {
                        alert("WebSocket 连接没有建立成功！");
                    }
                }
            }
        });
    };
    findFriend = function () {
        var $param = $("#param").val();
        console.log($param);
        if ($param === "") {
            // 提示输入
            alert("请输入用户名或邮箱进行查找！")
        } else {
            $.ajax({
                type: "GET",
                url: "user/find/" + $param,
                async: "false",
                success: function (result) {
                    var res = JSON.parse(result);
                    console.log(result);
                    if (result !== "null") {

                        $(".toAdd").removeClass("d-none");
                        // 设置用户名
                        $("#username").text(res.userName);
                        // 设置用户邮箱
                        $("#user_email").text(res.email);
                        // 设置好友头像
                        $("#findFriendImg").attr("src", res.imagePath);
                    } else {
                        $(".toAdd").addClass("d-none");
                        alert("用户不存在！")
                    }
                },
                error: function (msg) {
                    return false;
                }
            });
        }
    }
    cleanContent = function () {
        $(".toAdd").addClass("d-none");
    }
    acceptFriendRequest = function (e) {
        var followUserName = $("#loginedUserName").text();
        var userName = $(e).parent().prev().children("a").text();
        console.log(userName + "--->" + followUserName);
        $.ajax({
            type: "GET",
            url: "friend/accept/" + userName + "/" + followUserName,
            success: function (result) {
                console.log(result);
                if ("OK" === result) {
                    $("#friend-requests").children("li").each(function () {
                        let $name = $(this).children(".notification-event").children("a").text();
                        if (userName === $name && !$(this).children(".notification-icon").hasClass("d-none")) {
                            // 如果相等，则表示存在相同的请求，都将其隐藏
                            $(this).children(".notification-icon").addClass("d-none");
                            $(this).children(".notification-event").find("span").text("你同意了对方的请求，现在开始聊天吧！");
                            var temp = parseInt($('#request_number').text()) - 1;
                            $("#request_number").text(temp);
                        }
                    });
                    window.initFriendList();
                }
            },
            error: function () {

            }
        })
    };

    // 拒绝好友添加请求
    refuseToAccept = function (e) {
        var followUserName = $("#loginedUserName").text();
        var userName = $(e).parent().prev().children("a").text();
        console.log(userName + "--->" + followUserName);
        $.ajax({
            type: "GET",
            url: "friend/refuse/" + userName + "/" + followUserName,
            success: function (result) {
                console.log(result);
                if ("OK" === result) {
                    $("#friend-requests").children("li").each(function () {
                        let $name = $(this).children(".notification-event").children("a").text();
                        if (userName === $name && !$(this).children(".notification-icon").hasClass("d-none")) {
                            // 如果相等，则表示存在相同的请求，都将其隐藏
                            $(this).children(".notification-icon").addClass("d-none");
                            $(this).children(".notification-event").find("span").text("你拒绝了对方的好友请求！");
                            var temp = parseInt($('#request_number').text()) - 1;
                            $("#request_number").text(temp);
                        }
                    });
                }
            }
        });
    };

    // 删除通知，即相当于已读通知
    $("#notification-list").on("click", "#delete-notification", function () {
        var $e = $(this);
        var aUserName = $e.parent().prev().prev().children("div").find("a").text();
        var bUserName = $("#loginedUserName").text();
        var flag = $e.parent().prev().prev().children("div").find("p").text();
        console.log(aUserName + " " + bUserName + " " + flag);
        $.ajax({
            type: "GET",
            url: "request/message/read/notice/" + aUserName + "/" + bUserName + "/" + flag,
            success: function (result) {
                console.log("result----> " + result)
                if ("OK" === result) {
                    // 成功更新了通知状态
                    $e.parent().parent().addClass("d-none");
                    console.log($e.parent().parent())
                    var temp = parseInt($('#notification-number').text()) - 1;
                    $("#notification-number").text(temp);
                }
            }
        })
    });
    sendChatMessage = function (eventCode) {
        if (13 === eventCode) {
            console.log("敲了回车！");
            var friendName = $("#chat-title").text();
            var myName = $("#loginedUserName").text();
            var message = {};
            message.A = myName;
            message.B = friendName;
            message.content = $('#message-content').html().trim();
            console.info(message.content);
            if (message.content === "") {
                xtip.msg("不能发空消息");
                $("#message-content").blur();
                $("#message-content").empty();
                return false;
            } else {
                message.time = getDate();
                // 聊天消息
                message.flag = "4";
                console.log(message);
                socket.send(JSON.stringify(message));
                createEle();
                event.returnValue = false;
                $('#message-content').html('').focus();
                $("#show-content").scrollTop($("#show-content")[0].scrollHeight);
            }
        }

    };
    getDate = function () {
        var date = new Date();
        var sep1 = "-";
        var sep2 = ":";
        var year = date.getFullYear(); //年
        var month = date.getMonth() + 1; //月
        var day = date.getDate(); //日
        var hh = date.getHours(); //时
        var mm = date.getMinutes(); //分
        var ss = date.getSeconds();
        return year + sep1 + month + sep1 + day + " " + hh + sep2 + mm + sep2 + ss;
    };
    createEle = function () {
        var $content = $("#chat-message-field");
        var $li = $("<li class='my-message'></li>");
        var $div = $("<div  class=\"author-thumb\"></div>");
        var $img = $("<img src=\"img/author-page.jpg\" style='width: 28px; height: 28px' alt=\"author\" class=\"mCS_img_loaded\">");
        $img.attr("src", $("#user-img").attr("src"));
        $div.append($img);
        $li.append($div);
        $div = $("<div class=\"notification-event\"></div>");

        var $span = $("<span class=\"chat-message-item\" style='word-break:break-all; word-wrap:break-word;width: 80%'></span>");
        var content = $('#message-content').html().trim();
        $($.parseHTML(content, document, true)).appendTo($span);

        var $span1 = $("<span class=\"notification-date\"></span>");
        var $time = $("<time class=\"entry-date updated\"></time>");
        var currentdate = getDate();
        $time.text(currentdate);
        $span1.append($time);
        $div.append($span);
        $div.append($span1);
        $li.append($div);
        $content.append($li);
    };
    readAllChatMessage = function () {
        $.ajax({
            type: "GET",
            url: "chat/read-all/" + $("#loginedUserName").text(),
            success: function (result) {
                if (result === "ok") {
                    $("#chat-number").text(0);
                    // 清空ul列表
                    $("#chat-message").empty();
                }
            },
            error: function (e) {

            }
        })
    };
    // 创建好友添加通知标签块
    createAddFriendEle = function (json) {
        let $li = $("<li></li>");
        let $div = $("<div class=\"author-thumb\"></div>");
        let $img = $("<img src=\"img/avatar55-sm.jpg\" alt=\"author\">");
        $img.attr("src", json.aUserInfo.imagePath);
        $div.append($img);
        $li.append($div);
        $div = $("<div class=\"notification-event\"></div>");
        let $a = $("<a href=\"#\" class=\"h6 notification-friend\"></a>");
        let $span = $("<span></span>");
    }
});

$(document).on("click", ".chat-emotions li a", function () {
    console.info($(this));
    let $container = $("#message-content");
    let $img = $(this).children("img").clone();
    $container.append($img);
});

